package com.example.lss.news;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.lss.news.bean.User;
import com.example.lss.news.bean.UserBean;
import com.example.lss.news.dao.NewsDao;
import com.example.lss.news.utils.JsonUtils;
import com.example.lss.news.utils.app.BaseActivity;
import com.example.lss.news.utils.db.DBHelper;
import com.example.lss.news.utils.http.HttpUtils;
import com.example.lss.news.utils.http.JsonCallback;
import com.example.lss.news.utils.pic.CircleImageView;

import java.util.List;

import io.realm.RealmList;


public class RegisterActivity extends BaseActivity implements View.OnClickListener {

    private EditText acc, pwd, name, qianming, oneself;
    private CircleImageView head;
    private Button zhuce;
    private String accs;
    private String pwds;
    private String names;
    private String qianmings;
    private String oneselfs;
    private String ss;
    public static final int CHOOSE_PHOTO = 2;
    private String imagePath;
    static String impath;

    @Override
    protected int getLayoutId() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        return R.layout.activity_register;
    }

    @Override
    protected void initView() {
        acc = findViewById(R.id.acc);
        pwd = findViewById(R.id.pwd);
        name = findViewById(R.id.name);
        qianming = findViewById(R.id.qianming);
        oneself = findViewById(R.id.oneself);
        zhuce = findViewById(R.id.zhuce);
        head = findViewById(R.id.head);

    }

    @Override
    protected void initData() {
        accs = acc.getText().toString();
        pwds = pwd.getText().toString();
        names = name.getText().toString();
        qianmings = qianming.getText().toString();
        oneselfs = oneself.getText().toString();


    }

    @Override
    protected void initListener() {
        zhuce.setOnClickListener(this);
        head.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        if (view == zhuce) {
            final String url = "https://www.apiopen.top/createUser?key=00d91e8e0cca2b76f515926a36db68f5&phone=" + acc.getText().toString() + "&passwd=" + pwd.getText().toString() + "&img=" + impath + "&text=" + qianming.getText().toString();
//            showToast(url);

            HttpUtils.post(0, url, null, new JsonCallback() {
                @Override
                public void onStart(Object tag) {

                }

                @Override
                public void onSuccess(String json) {
                    UserBean<User> userBean = JsonUtils.toBean(json, JsonUtils.newParamType(UserBean.class,User.class));
                    if ("200".equals(userBean.getCode())) {
                        NewsDao dao = new NewsDao();
                        dao.add(userBean.getData());
                        finish();
                    }else {
                        showToast("账号已被注册！！!");
                    }

                }

                @Override
                public void onError(Throwable exception) {

                }

                @Override
                public void onFinish() {

                }
            });
        } else if (view == head) {
            if (ContextCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(RegisterActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

            } else {
                openAlbum();
            }
        }
    }

    private void openAlbum() {
        Intent it = new Intent("android.intent.action.GET_CONTENT");
        it.setType("image/");
        startActivityForResult(it, CHOOSE_PHOTO);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    showToast("You denied the permission");
                }
                break;
            default:
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case CHOOSE_PHOTO:
                if (Build.VERSION.SDK_INT >= 19) {
//                    >4.4
                    handleImageOnKitKat(data);
                } else {
                    handleImageBeforeKitKat(data);
                }
        }
    }


    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        imagePath = null;
        Uri uri = data.getData();
        Log.d("TAG", "handleImageOnKitKat: uri is " + uri);
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1]; // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是content类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        impath = imagePath;
        displayImage(imagePath); // 根据图片路径显示图片
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            head.setImageBitmap(bitmap);
        } else {
            Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
        }
    }
}
